#include "yb_form_jsdz.h"
#include "ui_yb_form_jsdz.h"
#include "pub_var.h"

#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QSettings>
#include <QMessageBox>
#include <QDebug>
#include <QSqlError>
#include <QSqlRecord>
#include <QDateTime>
#include <QFile>
#include <QFileDialog>
#include "zip/JlCompress.h"

Form_jsdz::Form_jsdz(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_jsdz)
{
    ui->setupUi(this);

    QSettings setIni("clin.ini", QSettings::IniFormat);

    //文件下载之后的存储路径
    downloadPath = setIni.value("system/downloadPath").toString();

    if(downloadPath.isEmpty()){
        //下载路径未设置，设置为默认值
        downloadPath = "/0down";
        setIni.setValue("system/downloadPath", "/0down");

    }

    QDir d(downloadPath);

    downloadPath = d.path(); //过滤配置文件可能出现的错误字符

    if( ! d.exists() ){
        //路径不存在，按指定的名字建立新路径

        if(!d.mkdir(downloadPath)){
            QMessageBox::warning(this, "注意", "指定文件存储路径无效！默认路径为本级盘符:\\0down\\");
            downloadPath = "/0down";
            setIni.setValue("system/downloadPath", downloadPath);
            d.setPath(downloadPath);
            if(!d.exists() && !d.mkdir(downloadPath)){
                QMessageBox::warning(this, "注意", "建立默认路径失败!");
            }
        }
    }

    //恢复当前窗口位置
    QRect rct = setIni.value("windowState/jsdz").toRect();
    this->setGeometry(rct);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);

    //默认日期
    QDate dt;
    ui->deStart->setDate(dt.currentDate());
    ui->deEnd->setDate(dt.currentDate());
    ui->deStart_2->setDate(dt.currentDate());
    ui->deEnd_2->setDate(dt.currentDate());

    request.setUrl(QUrl(pub::hos_ybjy));
    //request.setUrl(QUrl("http://192.168.1.233:9999"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
//    request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");

    //zip动态库存是否存在
    QString zipFile = pub::base_path + "/quazip.dll";
    QFile f;

    if(f.exists(zipFile) )
    {
        hasZip = true;
    } else {
        hasZip = false;
    }

    md_insu_sum = new QSqlQueryModel();

    ui->tab_main->setCurrentIndex(0);
    //检查用户权限
    has_insu_privilege = false; //预置为无权限

    sq = "select name from com_privileges where role_dept = '医保管理员'"
         " and name = '" + pub::usr_name + "'";
    qrm->exec(sq);

    if(qrm->next())
    {
        //有权限
        has_insu_privilege = true;
    }
}

Form_jsdz::~Form_jsdz()
{
    delete ui;
}

void Form_jsdz::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/jsdz", QVariant(this->geometry()));
    destroyW("jsdz");
}

void Form_jsdz::showEvent(QShowEvent *event)
{
    Q_UNUSED(event);
    //QMessageBox::information(this,"note","widnow is show");
}

void Form_jsdz::on_pbRun_clicked()
{
    //对总账
    QJsonObject in;
    if(! putBaseIn(  in, "3201") ){
        return;
    }

    QJsonObject inpu,inpud;

    //inpu.insert("insutype", ui->cbbXz->currentText());//险种
    inpu.insert("insutype", cur_insu_type);//险种
    inpu.insert("clr_type", ui->cbbQslb->currentText());//清算类别
    inpu.insert("setl_optins", pub::hos_insuplc);//结算经办机构
    //inpu.insert("setl_optins", pub::hos_ybbh_old);//结算经办机构
    //inpu.insert("setl_optins", pub::hos_ybbh);//结算经办机构
    inpu.insert("stmt_begndate", ui->deStart->date().toString("yyyy-MM-dd")+" 00:00:00");//对账开始日期
    inpu.insert("stmt_enddate", ui->deEnd->date().toString("yyyy-MM-dd")+" 23:59:59");//对账结束日期
    inpu.insert("medfee_sumamt", ui->le1->text());//医疗费总额
    inpu.insert("fund_pay_sumamt",ui->le2->text());//基金支付总额
    inpu.insert("acct_pay",ui->le3->text());//个人账户支付金额
    inpu.insert("fixmedins_setl_cnt",ui->le5->text());//定点医药机构结算笔数

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);
    qDebug()<<"3201 indoc "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    //request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。


    qDebug()<<" request 3201 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    QByteArray bt = reply->readAll();
    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());

        return ;
    }
    qDebug()<< "3201 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    sq = "update com_business set  tmstmp = now(), v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +  "  where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }


    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","3201 交易失败：" + t );

        return ;
    }
    ret3201 = jsob.value("output").toObject().value("stmtinfo").toObject();

    //qDebug()<<ret3201.value("setl_optins").toString();

    QString msg = ui->le_insu_type->text() + " : 对账返回结果";
    if(ret3201.value("stmt_rslt").toString() == "0")
    {
        msg += "正确。";
    }
    else
    {
        msg += "异常，" + ret3201.value("stmt_rslt_dscr").toString();
    }

    QMessageBox::information(this,"注意", msg);

}

void Form_jsdz::on_pbUpload_clicked()
{

    //明细对账

    QString fileName = QFileDialog::getOpenFileName(this, "打开准备上传的对账文件",  downloadPath,  "(*.txt)",  0);//*.zip
    if (fileName.isNull()){
        return;
    }

    QString  pureFileName,fileSuffix;
    QFileInfo fileinfo;
    fileinfo = QFileInfo(fileName);
    pureFileName = fileinfo.fileName();//文件名
    fileSuffix = fileinfo.suffix(); //扩展名

    if(!hasZip)//无zip库可用
    {
        QMessageBox::warning(this, "注意", "无可用zip库！"); //，请手工将txt文件压缩为zip格式
        return ;
    }

    if(!JlCompress::compressFile(fileName + ".zip", fileName))
    {
        QMessageBox::warning(this, "注意", "创建压缩文件失败！"); //，请手工将txt文件压缩为zip格式！
        return ;
    }
    fileName += ".zip";

    QByteArray bt;

    QFile f(fileName);
    if(!f.open(QIODevice::ReadOnly)){
        QMessageBox::information(this,"note","open file failed.");
        return;
    }
    bt = f.readAll();
    f.close();


    qDebug()<<bt;

    int len = bt.length();

    //base64方式传送
    QString btStr = QString::fromLatin1(bt.toBase64());
    QJsonValue btS0 = btStr;

    //char类型json数组传送
    QJsonArray jsar;
    for(int i = 0; i < len; i++){

        jsar.insert(i, char(bt[i]));

    }



    QJsonObject in;
    QJsonObject inpu,inpud;
    QJsonDocument d;

    if(!putBaseIn(  in, "9101") ){
        return;
    }


    inpu.insert("in",  btS0);//文件数据
    //inpu.insert("in",  jsar);//文件数据

    //inpu.insert("filename", pureFileName.left(pureFileName.length()-3) + "txt");//文件名
    inpu.insert("filename", pureFileName);//文件名
    inpu.insert("fixmedins_code", pub::hos_ybbh);//定点医药机构

    inpud.insert("fsUploadIn",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");


    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回。


    qDebug()<<" request 9101 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    QByteArray btret = reply->readAll();
    QString t = QString::fromLocal8Bit(btret);

    QJsonParseError json_error;

    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());

        return ;
    }
    qDebug()<< "9101 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    sq = "update com_business set  tmstmp = now(), v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +  "  where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }

    if(jsob.value("code").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","9101 交易失败：" + t );

        return ;
    }
    ret9101 = jsob.value("output").toObject();
    //.value("stmtinfo").toObject()

    qDebug()<<ret9101.value("file_qury_no").toString();


    //9101 结束



    //调用3202


    in = d.object();
    inpu = d.object();
    inpud = d.object();

    if(!putBaseIn(  in, "3202") ){
        return;
    }

    inpu.insert("setl_optins", pub::hos_insuplc);//	结算经办机构
    //inpu.insert("setl_optins", pub::hos_ybbh_old);//	结算经办机构
    //inpu.insert("setl_optins", pub::hos_ybbh);//	结算经办机构
    inpu.insert("file_qury_no", ret9101.value("file_qury_no").toString());//	文件查询号

    inpu.insert("stmt_begndate", ui->deStart->date().toString("yyyy-MM-dd")+" 00:00:00");//对账开始日期
    inpu.insert("stmt_enddate", ui->deEnd->date().toString("yyyy-MM-dd")+" 23:59:59");//对账结束日期

    inpu.insert("medfee_sumamt", ui->le1->text());//医疗费总额
    inpu.insert("fund_pay_sumamt",ui->le2->text());//基金支付总额

    //    inpu.insert("acct_pay",ui->le3->text());//个人账户支付金额
    inpu.insert("cash_payamt", ui->le4->text());//	现金支付金额

    inpu.insert("fixmedins_setl_cnt",ui->le5->text());//定点医药机构结算笔数
    //inpu.insert("clr_type","99959");    //清算方式
    //inpu.insert("refd_setl_flag","0");    //？
    inpud.insert("data",inpu);
    in.insert("input", inpud);

    indoc.setObject(in);
    qDebug()<<"3202 indoc "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    //request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
    reply = manager.post(request,indoc.toJson());

    //QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。


    qDebug()<<" request 3202 is returned";

    statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    btret = reply->readAll();
    t = QString::fromLocal8Bit(btret);

    //QJsonParseError json_error;

    jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);

    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
        return ;
    }
    qDebug()<< "3202 outDoc "<<jsdc;
    jsob = jsdc.object();

    sq = "update com_business set  tmstmp = now(), v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +  "  where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }

    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","3202 交易失败：" + t );
        return ;
    }
    ret3202 = jsob.value("output").toObject().value("fileinfo").toObject();

    qDebug()<<ret3202.value("file_qury_no").toString()
           <<ret3202.value("filename").toString()
          <<ret3202.value("dld_endtime").toString();

    //9102，下载对账结果

    in = d.object();
    inpu = d.object();
    inpud = d.object();

    if(!putBaseIn(  in, "9102") ){
        return;
    }

    inpu.insert("file_qury_no", ret3202.value("file_qury_no").toString());//	文件查询号
    inpu.insert("filename", ret3202.value("filename").toString());//
    inpu.insert("fixmedins_code", pub::hos_ybbh);//定点医药机构结

    inpud.insert("fsDownloadIn",inpu);
    in.insert("input", inpud);

    indoc.setObject(in);

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    //request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
    reply = manager.post(request,indoc.toJson());

    //QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request 9102 is returned";

    statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    bt = reply->readAll();

    QFile f1( downloadPath + "/" + pureFileName +  "-ret.zip");
    if(!f1.open(QIODevice::WriteOnly)){
        QMessageBox::information(this,"note","create download file failed.");
        return;
    }
    f1.write(bt);
    f1.close();

    QMessageBox::information(this,"注意","对账文件下载完成"  );

}

void Form_jsdz::on_pbExit_clicked()
{
    this->close();
}

bool Form_jsdz::putBaseIn( QJsonObject &in, QString code)
{
    QString inp;
    inp = pub::getYbStrJ(code,"");   //
    if(inp.isEmpty()){
        //pub::useInsurance = false;  //设置医保不可用
        QMessageBox::information(this,"note","申请交易流水号失败！");
        return false; //未能成功申请交易流水号
    }

    currentMsgid = inp;

    in.insert("infno", code);
    in.insert( "msgid", inp);
    in.insert("mdtrtarea_admvs", pub::hos_insuplc);
    //in.insert("insuplc_admdvs", mpPerson["insuplc_admdvs"] );

    in.insert("insuplc_admdvs","210100");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);

    return true;
}

void Form_jsdz::on_pbCalculate_clicked()
{

    QString dt0,dt1;
    dt0 = "'" + ui->deStart->date().toString("yyyy-MM-dd") + "','yyyy/mm/dd'";
    dt1 = "'" + ui->deEnd->date().addDays(1).toString("yyyy-MM-dd") + "','yyyy/mm/dd'";
    sq = " select case when base.insutype = '310' then '职工医保' else "
         " ( case when base.insutype = '390' then '居民医保' else '合计' end ) end 险种,"
         " to_char(tot_cost, '9999999.99') 总额,"
         " to_char(fund_pay_sumamt, '9999999.99') 基金支付,"
         " to_char(pay_cost, '9999999.99') 账户支付,"
         " to_char(own_cost, '9999999.99') 现金支付,"
         " bill_count 结算笔数,"
         " insutype, "
         " to_char(pay_cost + fund_pay_sumamt, '9999999.99') 基金申报总额"
         " from  "
         "( SELECT insutype, SUM (tot_cost) tot_cost, SUM (fund_pay_sumamt) fund_pay_sumamt,"
         " SUM (pay_cost) pay_cost, SUM (own_cost) own_cost, COUNT (*) bill_count"
         " FROM fin_ipr_siinmaininfo WHERE"
         " psn_no IS NOT NULL "
         "  AND oper_date > TO_DATE (%1)"
         "  AND oper_date < TO_DATE (%2)"
         " group by INSUTYPE"
         " UNION"
         " SELECT '999', SUM (tot_cost) ,SUM (fund_pay_sumamt) ,SUM (pay_cost),"
         " SUM (own_cost) ,COUNT (*) bill_count"
         " FROM fin_ipr_siinmaininfo "
         " WHERE psn_no IS NOT NULL"
         " AND oper_date > TO_DATE (%1)"
         " AND oper_date < TO_DATE (%2)"
         ") base"
         " order by INSUTYPE ";

    sq = sq.arg(dt0).arg(dt1);


    qDebug()<<sq;
    md_insu_sum->setQuery(sq, pub::db_o);

    if( md_insu_sum->rowCount() < 2 ){
        QMessageBox::information(this,"注意","找不到指定日期的数据！");
        return;
    }

    ui->tv_insu_sum->setModel(md_insu_sum);
    pub::setColumnWidth(ui->tv_insu_sum, "0.1^0.15^0.15^0.15^0.15^0.1^0^0.15", ui->tv_insu_sum->width());

    QModelIndex idx = md_insu_sum->index(0, 0);

    ui->le_insu_type->setText(idx.siblingAtColumn(0).data().toString());
    ui->le1->setText(idx.siblingAtColumn(1).data().toString().trimmed());
    ui->le2->setText(idx.siblingAtColumn(2).data().toString().trimmed());
    ui->le3->setText(idx.siblingAtColumn(3).data().toString().trimmed());
    ui->le4->setText(idx.siblingAtColumn(4).data().toString().trimmed());
    ui->le5->setText(idx.siblingAtColumn(5).data().toString().trimmed());
    cur_insu_type = idx.siblingAtColumn(6).data().toString();

    if(!ui->cbCreate->isChecked()){
        //未选择生成文件，直接退出
        return;
    }

    QString path = downloadPath + "/3202_" + QDateTime::currentDateTime().toString("yyyyMMddhhmmss") + ".txt";

    //创建文件对象
    QFile file;
    //关联文件名字
    file.setFileName(path);
    //打开文件,只写方式
qDebug()<<"filepath "<<path;
    bool isOK = file.open(QIODevice::WriteOnly);
    if (!isOK){
        QMessageBox::information(this,"注意","创建明细文件失败！");
        return;
    }

    sq = "select setl_id, mdtrt_id, psn_no, tot_cost, pub_cost, pay_cost, '0' "
         " from fin_ipr_siinmaininfo"
         //"  where psn_no is not null and oper_date > to_date('"
            " where psn_no is not null and insutype = '"
               + cur_insu_type + "' and oper_date > to_date('"  //ui->cbbXz->currentText()
            + ui->deStart->date().toString("yyyy-MM-dd")
            +"','yyyy/mm/dd') and oper_date< to_date('"
            + ui->deEnd->date().toString("yyyy-MM-dd")
            +" 23:59:59','yyyy/mm/dd hh24:mi:ss')" ;
    qDebug()<<sq;
    qro->exec(sq);
    ui->lwResult->clear();
    QString str ;
    while(qro->next()){
        str = qro->value(0).toString();
        str.append("\t");
        str.append(qro->value(1).toString());
        str.append("\t");
        str.append(qro->value(2).toString());
        str.append("\t");
        str.append(QString::asprintf("%.2f",qro->value(3).toDouble()));
        str.append("\t");
        str.append(QString::asprintf("%.2f",qro->value(4).toDouble()));
        str.append("\t");
        str.append(QString::asprintf("%.2f",qro->value(5).toDouble()));
        str.append("\t");
        str.append(qro->value(6).toString() + "\r\n");

        file.write(str.toLatin1());
        ui->lwResult->addItem(str);
    }
    file.close();

    //write files
    //QString -> QByteArray
    // file.write(str.toUtf8());
    //QString -> C++ string ->char*
    //file.write(str.toStdString().data());
    QMessageBox::information(this,"注意", path+" 文件已生成！");

}

void Form_jsdz::on_tv_insu_sum_clicked(const QModelIndex &index)
{
    if(index.siblingAtColumn(6).data().toString() == "999")
    {
        //合计
        return;
    }

    ui->le_insu_type->setText(index.siblingAtColumn(0).data().toString());
    ui->le1->setText(index.siblingAtColumn(1).data().toString().trimmed());
    ui->le2->setText(index.siblingAtColumn(2).data().toString().trimmed());
    ui->le3->setText(index.siblingAtColumn(3).data().toString().trimmed());
    ui->le4->setText(index.siblingAtColumn(4).data().toString().trimmed());
    ui->le5->setText(index.siblingAtColumn(5).data().toString().trimmed());
    cur_insu_type = index.siblingAtColumn(6).data().toString();
}

void Form_jsdz::on_tv_insu_sum_doubleClicked(const QModelIndex &index)
{
    on_tv_insu_sum_clicked(index);
}

void Form_jsdz::on_pbSearch_clicked()
{
    if(!has_insu_privilege)
    {
        QMessageBox::information(this,"注意","此操作需要“医保管理员”权限！");
        return;
    }

    ui->lwMsgid->clear();
    ui->pt_msg_detail->clear();

    QString codeList = "'code'";

    ui->lwMsgid->clear();

    QString cond = " ywbh in ('2207A','2208') and ";


    //查询 fin_ipr_siinmaininfo 中保存的msgid
    sq = " select msgid "
         " from fin_ipr_siinmaininfo "
         " where oper_date > to_date('%1','yyyy/mm/dd') "
         " and oper_date< to_date('%2 23:59:59','yyyy/mm/dd hh24:mi:ss')";

    sq = sq.arg(ui->deStart_2->date().toString("yyyy-MM-dd"))
            .arg(ui->deEnd_2->date().toString("yyyy-MM-dd"));

    qro->exec(sq);

    qDebug() << "查询 fin_ipr_siinmaininfo 中保存的 msgid : " << sq <<"\n";

    QStringList id_list;

    while(qro->next())
    {
        id_list << qro->value(0).toString();
        //qDebug()<<qro->value(0).toString();

    }

//    if(id_list.isEmpty())
//    {
//        QMessageBox::information(this,"注意","指定日期范围没有医保结算记录 ！");
//        return;
//    }

    sq = "select jyls, jysj, ywbh, jyfs,infcode from com_business where "
            + cond
            + " jysj > '"
            + ui->deStart_2->date().toString("yyyy-MM-dd")
            +" 00:00:00' and jysj< '"
            + ui->deEnd_2->date().toString("yyyy-MM-dd")
            +" 23:59:59' and jyls not in('"  //
            + id_list.join("','") + "' ) order by atinc";
    qDebug() << "查询 com_business 中有记录，fin_ipr_siinmaininfo 中无记录的无效 msgid " ;
    qDebug() << sq << "\n";

    qrm->exec(sq);

    while(qrm->next())
    {
        QString msg = qrm->value(0).toString()
                +"\t"
                +qrm->value(1).toString()
                +"\t"
                +qrm->value(2).toString()
                +"\t"
                +qrm->value(3).toString();
        if(qrm->value(4).toInt() != 0)
        {
            msg += "交易失败";
        }
        ui->lwMsgid->addItem(msg);
    }

    if(ui->lwMsgid->count() < 1)
    {
        QMessageBox::information(this,"注意","指定日期范围找不到无效的 MsgId ！");
        return;
    }
}

void Form_jsdz::on_pb2601_clicked()
{
    if(!has_insu_privilege)
    {
        QMessageBox::information(this,"注意","此操作需要“医保管理员”权限！");
        return;
    }

    if(ui->lePsnno->text().isEmpty() || ui->leMsgid->text().isEmpty())
    {
        QMessageBox::information(this,"注意","未选择需要冲正的 msgid！");
        return;
    }

    //核实操作确认
    QMessageBox:: StandardButton result=
            QMessageBox::warning(NULL, "注意", "此操作不可撤销，确定要继续？",QMessageBox::Yes|QMessageBox::No);
    if(result == QMessageBox::No)
    {
        return;
    }

    QJsonObject in;
    putBaseIn(  in, "2601") ;

    QJsonObject inpu,inpud;

    inpu.insert("psn_no", ui->lePsnno->text());//psn_no
    inpu.insert("omsgid", ui->leMsgid->text());//
    inpu.insert("oinfno", oinfno);//


    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);
    qDebug()<<"2601 indoc "<<indoc;

    //保存入参日志
    sq = "update com_business set clinic_code = '" + clinic_code + "',v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request 2601 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid())
    {
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    QByteArray bt = reply->readAll();
    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());

        return ;
    }
    qDebug()<< "2601 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    sq = "update com_business set  tmstmp = now(), v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +  "  where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }


    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","2601 交易失败：" + t );
        return ;
    }

    QString stat = ui->le_status->text();

    if(stat.indexOf("已冲正") < 0)
    {
        stat += "已冲正";
    }

    sq = " update com_business set jyfs = '" + stat + "' "
         " where jyls = '" + ui->leMsgid->text() + "'";

    qDebug()<<"保存冲正标志:"<<sq<<"\n";
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","保存冲正标志失败！");
    }

    QMessageBox::information(this,"注意","冲正操作结束！");

    ui->leXm->clear();
    ui->leMzh->clear();
    ui->leJzid->clear();
    ui->leClinicCode->clear();
    ui->leMsgid->clear();
    ui->lePsnno->clear();
    ui->le_status->clear();

}

void Form_jsdz::on_lwMsgid_doubleClicked(const QModelIndex &index)
{
    ui->leMsgid->setText( pub::getStr(ui->lwMsgid->item(index.row())->text(),"\t",1));
    oinfno = pub::getStr(ui->lwMsgid->item(index.row())->text(),"\t",3).left(4);    //有些编号带 A, 过滤掉。
    ui->le_status->setText(pub::getStr(ui->lwMsgid->item(index.row())->text(),"\t",4));

    sq = "select v_in, v_out, clinic_code, atinc,jyfs "
         " from com_business where jyls = '" + ui->leMsgid->text() + "'";
    qrm->exec(sq);
    qrm->next();

    QJsonDocument jsdc = QJsonDocument::fromJson(qrm->value(1).toString().toUtf8());
    ob_v_out_2207 = jsdc.object();

    clinic_code = qrm->value(2).toString();
    QString atinc = qrm->value(3).toString();

    //查询对应数据

    if(clinic_code.isEmpty())
    {
        QMessageBox::information(this, "Note", "clinic_code 为空，无法查询 fin_ipr_siinmaininfo 的基本信息");
        return;
    }

    sq = " select name, card_no, mdtrt_id, psn_no "
         " from fin_ipr_siinmaininfo "
         " where inpatient_no = '" + clinic_code + "'";
    qro->exec(sq);
    qro->next();
    qDebug()<<"查询 fin_ipr_siinmaininfo 表中保存的基本信息";
    qDebug()<<sq;

    psn_no = qro->value("psn_no").toString();
    ui->lePsnno->setText(psn_no);

    ui->leXm->setText(qro->value("name").toString());
    ui->leMzh->setText(qro->value("card_no").toString());
    ui->leJzid->setText(qro->value("mdtrt_id").toString());
    ui->leClinicCode->setText(clinic_code);

    sq = "select v_in, v_out, clinic_code, atinc "
         " from com_business where clinic_code = '"
            + clinic_code + "' and atinc < "
            + atinc + " and ywbh = '2204' order by atinc desc";
    qrm->exec(sq);
    qrm->next();

    qDebug()<<"查询 MsgID 关联的费用明细信息";
    qDebug()<<sq;

    jsdc = QJsonDocument::fromJson(qrm->value(0).toString().toUtf8());
    QJsonObject jsob = jsdc.object();
    QJsonArray jsar = jsob.value("input").toObject().value("feedetail").toArray();



    ui->pt_msg_detail->clear();

    for(const QJsonValue &value : jsar)
    {
        QJsonObject obj = value.toObject();
        QString item_code = obj["medins_list_codg"].toString();
        //QString num = obj["cnt"].toString();
        double cnt = 0;
        if(obj["cnt"].isDouble())
        {
            cnt = obj["cnt"].toDouble();
        }
        else
        {
            cnt = obj["cnt"].toString().toDouble();
        }

        double pric = obj["pric"].toString().toDouble();

        double acount = cnt * pric;

        sq = "select his_name from fin_com_compare"
             " where fixmedins_hilist_id = '" + item_code + "'";
        qro->exec(sq);
        qro->next();

        QString item_name = qro->value(0).toString();

        ui->pt_msg_detail->appendPlainText(item_name + " , "
                                           + QString::asprintf("%.2f", cnt) + " * "
                                           + QString::asprintf("%.2f", pric) + " = "
                                            + QString::asprintf("%.2f", acount));
    }

}

void Form_jsdz::on_pb_2208_clicked()
{
    if(!has_insu_privilege)
    {
        QMessageBox::information(this,"注意","此操作需要“医保管理员”权限！");
        return;
    }

    if(ui->lePsnno->text().isEmpty() || ui->leMsgid->text().isEmpty())
    {
        QMessageBox::information(this,"注意","未选择需要退费的 msgid！");
        return;
    }

    //核实操作确认
    QMessageBox:: StandardButton result=
            QMessageBox::warning(NULL, "注意", "此操作不可撤销，确定要继续？",QMessageBox::Yes|QMessageBox::No);
    if(result == QMessageBox::No)
    {
        return;
    }

    QJsonObject in;
    putBaseIn(  in, "2208") ;

    QJsonObject inpu,inpud;

    inpu.insert("setl_id", ob_v_out_2207.value("output").toObject()
                .value("setlinfo").toObject()
                .value("setl_id").toString()); //
    inpu.insert("mdtrt_id",ob_v_out_2207.value("output").toObject()
                .value("setlinfo").toObject()
                .value("mdtrt_id").toString()); //
    inpu.insert("psn_no", ob_v_out_2207.value("output").toObject()
                .value("setlinfo").toObject()
                .value("psn_no").toString());      //

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);

    //保存入参日志
    sq = "update com_business set clinic_code = '" + clinic_code + "',v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","2208保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request 2208 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid())
    {
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError)
    {
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    QByteArray bt = reply->readAll();
    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);

    if(json_error.error != 0 )
    {
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
        return ;
    }

    qDebug()<< "2208 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    QString out_str = jsdc.toJson(QJsonDocument::Compact);
    out_str.replace("'","\\'");

    sq = "update com_business set  tmstmp = now(), v_out = '"
            + out_str
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +   " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }

    if(jsob.value("infcode").toInt() != 0)
    {
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","2208 交易失败：" + t );

        return ;
    }

    QString stat = ui->le_status->text();

    if(stat.indexOf("已退费") < 0)
    {
        stat += "已退费";
    }

    sq = " update com_business set jyfs = '" + stat + "' "
         " where jyls = '" + ui->leMsgid->text() + "'";

    qDebug()<<"保存退费标志:"<<sq<<"\n";
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","保存退费标志失败！");
    }

    QMessageBox::information(this,"注意","退费操作结束！");

    ui->leXm->clear();
    ui->leMzh->clear();
    ui->leJzid->clear();
    ui->leClinicCode->clear();
    ui->leMsgid->clear();
    ui->lePsnno->clear();
    ui->le_status->clear();
}

void Form_jsdz::on_lwMsgid_clicked(const QModelIndex &index)
{

}
